
from os.path import split, splitext, abspath, relpath, exists, sep, isfile, isdir
from os import getcwd, chdir, remove
from shutil import copyfile,move
from typing import Union
from tkinter import filedialog
import pypdftk
import re

def replace_ext(filename, ext='.pdf'):
    filepath = abspath(filename)
    directory, filename = split(filepath)
    basename, _ = splitext(filename)
    return abspath(directory + sep + basename + ext)

def uigetfile():
    file = filedialog.askopenfile()
    if file is None:
        return None
    return file.name

def mktemp(ext):
    import tempfile
    filepath = tempfile.mkstemp()[1]
    _, filename = split(filepath)
    return filename + ext

class WorkingDir:
    def __init__(self, path):
        if isfile(path):
            self.Directory, _ = split(path)
        else:
            path = abspath(path)
            if isdir(path):
                self.Directory = path
            else:
                raise IOError('path {} is neither file nor directory'.format(path))

    def __enter__(self):
        self.Restore = getcwd()
        chdir(self.Directory)

    def __exit__(self, exc_type, exc_val, exc_tb):
        chdir(self.Restore)

